package com.enation.app.javashop.consumer.shop.shop;

import com.enation.app.javashop.consumer.core.event.ShopChangeEvent;
import com.enation.app.javashop.core.aftersale.service.AfterSaleManager;
import com.enation.app.javashop.core.client.goods.GoodsClient;
import com.enation.app.javashop.core.client.goods.GoodsIndexClient;
import com.enation.app.javashop.core.goods.model.dos.GoodsDO;
import com.enation.app.javashop.core.goods.model.dto.GoodsQueryParam;
import com.enation.app.javashop.core.goods.service.GoodsManager;
import com.enation.app.javashop.core.goods.service.GoodsQueryManager;
import com.enation.app.javashop.core.goodssearch.service.GoodsIndexManager;
import com.enation.app.javashop.core.promotion.coupon.service.CouponManager;
import com.enation.app.javashop.core.shop.model.dos.ShipTemplateDO;
import com.enation.app.javashop.core.shop.model.dos.ShopDO;
import com.enation.app.javashop.core.shop.model.dos.ShopDetailDO;
import com.enation.app.javashop.core.shop.model.enums.ShopTemplateTypeEnum;
import com.enation.app.javashop.core.shop.model.vo.ShipTemplateChangeMsg;
import com.enation.app.javashop.core.shop.model.vo.ShipTemplateSellerVO;
import com.enation.app.javashop.core.shop.model.vo.ShopChangeMsg;
import com.enation.app.javashop.core.shop.model.vo.ShopVO;
import com.enation.app.javashop.core.shop.service.ShipTemplateLocalManager;
import com.enation.app.javashop.core.shop.service.ShipTemplateManager;
import com.enation.app.javashop.core.shop.service.ShopManager;
import com.enation.app.javashop.core.trade.order.service.OrderOperateManager;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.logs.Debugger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 店铺信息同步
 *
 * @author Chopper
 * @version v1.0
 * @since v7.0
 * 2018-12-10 下午4:05
 */
@Component
public class ShopLocationOrTemplateChangeConsumer implements ShopChangeEvent {
    @Autowired
    private GoodsIndexManager goodsIndexManager;
    @Autowired
    private GoodsQueryManager goodsQueryManager;


    @Autowired
    private Debugger debugger;


    protected final Log logger = LogFactory.getLog(this.getClass());


    /**
     * 店铺地址改变重建店铺商品索引
     *
     * @param shopChangeMsg 店铺名称改变消息
     */
    @Override
    public void shopChange(ShopChangeMsg shopChangeMsg) {
        try {
            //原店铺数据
            ShopVO originalShop = shopChangeMsg.getOriginalShop();
            //更新后店铺数据
            ShopVO shop = shopChangeMsg.getNewShop();
            // 只有商铺坐标变更之后才重新修改商品位置
            if (!(originalShop.getShopLat().equals(shop.getShopLat()) && originalShop.getShopLng().equals(shop.getShopLng()))) {
                updateGoodsIndexByShop(shop);
            }

        } catch (Exception e) {
            logger.error("处理店铺地址改变出错" + e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 同城配送模板修改消息
     *
     * @param shipTemplateChangeMsg 同城配送模板修改消息
     */
    public void shipTemplateChange(ShipTemplateChangeMsg shipTemplateChangeMsg) {
        try {
            ShipTemplateDO originalTemplate = shipTemplateChangeMsg.getOriginalTemplate();
            ShipTemplateDO newTemplate = shipTemplateChangeMsg.getNewTemplate();
            if (!newTemplate.equals(originalTemplate)) {
                updateGoodsIndexByLocalTemp(newTemplate);
            }

        } catch (Exception e) {
            logger.error("同城配送模板修改消息失败" + e.getMessage());
            e.printStackTrace();
        }
    }

    private void updateGoodsIndexByLocalTemp(ShipTemplateDO localTemp) {
        // 查询同城配送模板商品数量
        GoodsDO queryGoodsDO = new GoodsDO();
        queryGoodsDO.setDisabled(1);
        queryGoodsDO.setLocalTemplateId(localTemp.getId());
        Integer goodsCount = this.goodsQueryManager.getGoodsCountByParam(queryGoodsDO);
        int pageSize = 100;
        int pageCount;
        pageCount = goodsCount / pageSize;
        pageCount = goodsCount % pageSize > 0 ? pageCount + 1 : pageCount;
        for (int i = 1; i <= pageCount; i++) {
            GoodsQueryParam goodsQueryParam = new GoodsQueryParam();
            goodsQueryParam.setPageNo(i);
            goodsQueryParam.setPageSize(pageSize);
            goodsQueryParam.setLocalTemplateId(localTemp.getId());
            List<Map> goodsList = goodsQueryManager.list(goodsQueryParam).getData();
            Integer[] goodsIds = new Integer[goodsList.size()];
            int j = 0;
            for (Map map : goodsList) {
                goodsIds[j] = Integer.valueOf(map.get("goods_id").toString());
                j++;
            }
            // 根据待更新商品IDS 查询对应商品
            List<Map<String, Object>> list = goodsQueryManager.getGoodsAndParams(goodsIds);
            // 店铺属性信息
            for (Map<String, Object> goods : list) {
                // 同城配送信息
                this.composeShipInfo(goods, localTemp);
                debugger.log("=====================开始更新索引" + goods.get("goods_Id").toString() + "========================");
                this.goodsIndexManager.updateIndex(goods);
            }
        }

    }

    private void updateGoodsIndexByShop(ShopVO shopDetail) {
        // 查询店铺商品数量
        GoodsDO queryGoodsDO = new GoodsDO();
        queryGoodsDO.setDisabled(1);
        queryGoodsDO.setSellerId(shopDetail.getShopId());
        Integer goodsCount = this.goodsQueryManager.getGoodsCountByParam(queryGoodsDO);
        int pageSize = 100;
        int pageCount;
        pageCount = goodsCount / pageSize;
        pageCount = goodsCount % pageSize > 0 ? pageCount + 1 : pageCount;
        for (int i = 1; i <= pageCount; i++) {
            GoodsQueryParam goodsQueryParam = new GoodsQueryParam();
            goodsQueryParam.setPageNo(i);
            goodsQueryParam.setPageSize(pageSize);
            goodsQueryParam.setSellerId(shopDetail.getShopId());
            List<Map> goodsList = goodsQueryManager.list(goodsQueryParam).getData();
            Integer[] goodsIds = new Integer[goodsList.size()];
            int j = 0;
            for (Map map : goodsList) {
                goodsIds[j] = Integer.valueOf(map.get("goods_id").toString());
                j++;
            }
            // 根据待更新商品IDS 查询对应商品
            List<Map<String, Object>> list = goodsQueryManager.getGoodsAndParams(goodsIds);
            // 店铺属性信息
            for (Map<String, Object> goods : list) {
                // 同城配送信息
                this.composeShopInfo(goods, shopDetail);
                debugger.log("=====================开始更新索引" + goods.get("goods_Id").toString() + "========================");
                this.goodsIndexManager.updateIndex(goods);
            }
        }

    }


    private void composeShopInfo(Map goods, ShopVO shopDetail) {
        goods.put("shop_logo", shopDetail.getShopLogo());
        goods.put("shop_lat", shopDetail.getShopLat());
        goods.put("shop_lng", shopDetail.getShopLng());
    }


    private void composeShipInfo(Map goods, ShipTemplateDO shipTemplate) {
        // 费用设置
        goods.put("ship_fee_setting", shipTemplate.getFeeSetting());
        // 时间设置
        goods.put("ship_time_setting", shipTemplate.getTimeSetting());
        // 起步价
        goods.put("base_ship_price", shipTemplate.getBaseShipPrice());
        // 配送范围
        goods.put("ship_range", shipTemplate.getShipRange());
    }

}
